const fs = require('fs');
const path = require('path');

// 默认服务器配置
const defaultConfig = {
  // RTMP server configuration - 优化延迟配置
  rtmp: {
    port: 1937,
    chunk_size: 4096,        // 减小块大小以降低延迟
    gop_cache: false,        // 禁用GOP缓存以减少延迟
    ping: 30,
    ping_timeout: 60
  },
  
  // HTTP server configuration - 优化FLV流配置
  http: {
    port: 8002,
    allow_origin: '*',
    mediaroot: './src/public',
    webroot: './src/public'
  },
  
  // Relay configuration for forwarding streams
  relay: {
    // Forwarding to other RTMP servers
    ffmpeg: {
      path: './ffmpeg.exe', // Path to ffmpeg executable
      options: [
        '-i', 'rtmp://localhost/live/{stream_name}',
        '-c:v', 'libx264',
        '-c:a', 'aac',
        '-f', 'flv',
        'rtmp://other-server/live/{stream_name}'
      ]
    }
  },
  
  // Authentication configuration
  auth: {
    api: true,
    api_user: 'admin',
    api_pass: 'admin'
  }
};

// 尝试从外部配置文件加载配置
let externalConfig = {};
try {
  const externalConfigPath = path.resolve(process.cwd(), 'config', 'server.config.json');
  if (fs.existsSync(externalConfigPath)) {
    externalConfig = JSON.parse(fs.readFileSync(externalConfigPath, 'utf8'));
    console.log('已加载外部服务器配置文件');
  }
} catch (error) {
  console.warn('加载外部服务器配置文件失败，使用默认配置:', error.message);
}

// 合并配置，外部配置优先
const config = JSON.parse(JSON.stringify({ ...defaultConfig, ...externalConfig }));

module.exports = config;